package com.res.share.controller;

import com.res.share.common.Constants;
import com.res.share.common.exception.BusinessException;
import com.res.share.common.utils.IpAddressUtils;
import com.res.share.common.utils.UserIdConvertor;
import com.res.share.service.IResLookService;
import com.res.share.service.IndexService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 试图跳转
 */
@Controller
public class IndexController extends BaseController {

    @Autowired
    private IndexService indexService;

    @Autowired
    private IResLookService resLookService;


    @Autowired
    private ThreadPoolExecutor executor;


    @Value("${file.doc-dir}")
    private  String UPLOAD_PATH;

    /**
     * 首页
     *
     * @param model
     * @return
     */
    @GetMapping(value = {"/"})
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> resultMap = indexService.findWebIndexData(request, response);
        model.addAttribute("title", "网站标题");
        model.addAttribute("desc", "网站标题");
        model.addAttribute("keyword", "网站标题");
        model.addAllAttributes(resultMap);
        return "index";
    }

    /**
     * 关于我们
     *
     * @return
     */
    @GetMapping(value = {"/limitIp/overLimitIP.html"})
    public String limitIp(Model model,HttpServletRequest request) {
        String remainingTime = request.getParameter("remainingTime");
        model.addAttribute("remainingTime",remainingTime);
        return "overLimitIP";
    }
    /**
     * 关于我们
     *
     * @return
     */
    @GetMapping(value = {"/web/me.html"})
    public String webPage() {
        return "me";
    }

    /**
     * 标签页
     *
     * @return
     */
    @GetMapping(value = {"/web/tags.html"})
    public String webtags() {
        return "tags";
    }

    /**
     * 搜索
     * @param model
     * @return
     */
    @GetMapping(value = {"/web/search.html"})
    public String search(HttpServletRequest request,@RequestParam(value = "keywords") String keywords,
                         @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, Model model) {
        model.addAttribute("title", "网站标题");
        model.addAttribute("desc", "网站标题");
        model.addAttribute("keyword", "网站标题");
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        Map<String, Object> resultMap = indexService.searchArticleList(pageNum,userId,keywords);
        model.addAllAttributes(resultMap);
        model.addAttribute("requestUrl", "/web/search.html");
        return "search";
    }

    /**
     * @param login
     * @param redirtUrl
     * @param model
     * @return
     */
    @GetMapping(value = {"/to/{login}.html"})
    public String commomPage(@PathVariable(value = "login") String login, Model model,
                             @RequestParam(value = "redirectUrl",required = false) String redirtUrl) {
        if (login.equalsIgnoreCase("login")) {
            long l = System.currentTimeMillis();
            String convert = UserIdConvertor.convert(l);
            model.addAttribute("codeUUId", UserIdConvertor.convert(convert));
        }
        if(StringUtils.isNotEmpty(redirtUrl)){
            model.addAttribute("redirectUrl", redirtUrl);
        }
        return login;
    }

    /**
     * 热门消息
     *
     * @param model
     * @return
     */
    @GetMapping(value = {"/web/hotmsg.html"})
    public String hotMessageList(HttpServletRequest request, @RequestParam(value = "hotType", required = false, defaultValue = "0") Integer hotType,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, Model model) {
        model.addAttribute("title", "网站标题");
        model.addAttribute("desc", "网站标题");
        model.addAttribute("keyword", "网站标题");
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        Map<String, Object> resultMap = indexService.findHotArticleList(userId, hotType, pageNum);
        model.addAllAttributes(resultMap);
        model.addAttribute("hotType", hotType);
        return "hotmessage";
    }


    /**
     * 分类资源
     *
     * @param request
     * @param model
     * @return
     */
    @GetMapping(value = {"/cate/{levelOneName}/{levelTwoName}/index.html"})
    public String findArticleByCateId(@PathVariable(value = "levelOneName") String levelOneName,
                                      @RequestParam(value = "hotType", required = false, defaultValue = "0") Integer hotType,
                                      @PathVariable(value = "levelTwoName") String levelTwoName,
                                      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      HttpServletRequest request, Model model) {
        model.addAttribute("title", "网站标题");
        model.addAttribute("desc", "网站标题");
        model.addAttribute("keyword", "网站标题");
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        Map<String, Object> resultMap = indexService.findArticleByCateId(userId, 1, levelOneName, levelTwoName, pageNum);
        model.addAllAttributes(resultMap);
        model.addAttribute("hotType", hotType);
        model.addAttribute("requestUrl", "/cate/" + levelOneName + "/" + levelTwoName + "/index.html");
        return "cat-article";
    }

    /**
     * 分类资源 -父类
     *
     * @param levelOneName
     * @param request
     * @param model
     * @return
     */
    @GetMapping(value = {"/cate/{levelOneName}/index.html"})
    public String findArticleByPidCateId(@PathVariable(value = "levelOneName") String levelOneName,
                                         @RequestParam(value = "hotType", required = false, defaultValue = "0") Integer hotType,
                                         @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                         HttpServletRequest request, Model model) {
        model.addAttribute("title", "网站标题");
        model.addAttribute("desc", "网站标题");
        model.addAttribute("keyword", "网站标题");
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        Map<String, Object> resultMap = indexService.findArticleByCateId(userId, 1, levelOneName, null, pageNum);
        model.addAllAttributes(resultMap);
        model.addAttribute("hotType", hotType);
        model.addAttribute("requestUrl", "/cate/" + levelOneName + "/index.html");
        return "cat-article";
    }


    /**
     * 退出系统
     *
     * @return RestResponse
     */
    @GetMapping("/web/logout.html")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(Constants.CURRENT_USER);
        return "redirect:/";
    }



    /**
     * 文章详情
     * @param request
     * @param model
     * @return
     */
    @GetMapping(value = {"/web/art-detail/{articleId}.html"})
    public String findArtDetail(HttpServletRequest request,HttpServletResponse response,
                                Model model,@PathVariable(value = "articleId") Integer articleId) {
        model.addAttribute("title", "网站标题");
        model.addAttribute("desc", "网站标题");
        model.addAttribute("keyword", "网站标题");
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        Map<String, Object> resultMap = indexService.findArtDetail(userId,articleId);
        if(resultMap == null ||  resultMap.get("articleModel")==null){
            throw new BusinessException("文章不存在",400);
        }

        //更新浏览量
        Integer finalUserId = userId;
        CompletableFuture.runAsync(()->{
            String ipAddr = IpAddressUtils.getIpAddress(request);
            List<Integer> artIdList=resLookService.findArtLookData(ipAddr);
            if(!CollectionUtils.isEmpty(artIdList)){
                if(!artIdList.contains(articleId)){
                    artIdList.add(articleId);
                    indexService.updateArticleLookSee(articleId);
                    resLookService.saveArtLookSee(articleId,ipAddr);
                }
            }else {
                indexService.updateArticleLookSee(articleId);
                resLookService.saveArtLookSee(articleId,ipAddr);
            }
            if(finalUserId !=null){
                indexService.saveArticleHistory(articleId,finalUserId);
            }
        },executor);
        model.addAllAttributes(resultMap);
        model.addAttribute("requestUrl","/web/art-detail/"+articleId+".html");
        return "art-detail";
    }

    //标签页所属文章列表
    @GetMapping(value = {"/tag/{tagpinyin}.html"})
    public String findTagArticleList(Model model, HttpServletRequest request,
                                 @PathVariable(value = "tagpinyin") String tagpinyin,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        model.addAttribute("title", "网站标题");
        model.addAttribute("desc", "网站标题");
        model.addAttribute("keyword", "网站标题");
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        Map<String, Object> resultMap = indexService.findTagArticleList(pageNum,userId,tagpinyin);
        model.addAllAttributes(resultMap);
        model.addAttribute("requestUrl", "/tag/"+tagpinyin+".html");
        return "tag-article";
    }



    /**
     * 使用流将图片输出
     *
     * @param response
     * @param name
     * @throws IOException
     */
    @GetMapping("/getImage/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        response.setContentType("image/jpeg;charset=utf-8");
        response.setHeader("Content-Disposition", "inline; filename=girls.png");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(Files.readAllBytes(Paths.get(UPLOAD_PATH).resolve(name)));
        outputStream.flush();
        outputStream.close();
    }

    //查询用户个人中心的文章列表

    /**
     * @param request
     * @param model
     * @return
     */
    @GetMapping(value = {"/usershop/{beLongUserId}.html"})
    public String findUserSHopResList(@PathVariable(value = "beLongUserId") Integer beLongUserId,@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,HttpServletRequest request, Model model) {
        model.addAttribute("title", "网站标题");
        model.addAttribute("desc", "网站标题");
        model.addAttribute("keyword", "网站标题");
        Integer userId = null;
        Object attribute = request.getSession().getAttribute(Constants.CURRENT_USER);
        if (attribute != null && StringUtils.isNotEmpty(attribute.toString())) {
            userId = Integer.valueOf(attribute.toString());
        }
        Map<String, Object> resultMap = indexService.findUserSHopResList(userId, beLongUserId, pageNum);
        model.addAllAttributes(resultMap);
        model.addAttribute("followFlag", 0);
        if(userId!=null && beLongUserId==userId){
            model.addAttribute("followFlag", 1);
        }
        model.addAttribute("requestUrl", "/usershop/"+beLongUserId+".html");
        return "person-res";
    }



}
